package com.ayg.test.apitest.dao;

import com.ayg.test.apitest.utils.DataSourceByC3p0;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ArrayListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class BaseDao {
    private static final Logger logger = LoggerFactory.getLogger(BaseDao.class);
    private static final String CONTENT = "content:{}";
    public Map query(String env,String sql, Object... params) {
        try {
            return DataSourceByC3p0.getQueryRunner(env).query(sql,new MapHandler(),params);
        } catch (SQLException e) {
            logger.error(CONTENT,e);
        }
        return null;
    }

    public List query(String env, String sql) {
        try {
            return DataSourceByC3p0.getQueryRunner(env).query(sql,new ArrayListHandler());
        } catch (SQLException e) {
            logger.error(CONTENT,e);
        }
        return null;
    }

    public int insert(String sql, Object... params){
        Long id = 0L;
        try {
            QueryRunner queryRunner = DataSourceByC3p0.getQueryRunner();
            id =(Long) queryRunner.insert(sql,new ScalarHandler(1),params);
        } catch (SQLException e) {
            logger.error(CONTENT,e);
        }
        return id.intValue();
    }

    public void update(String sql, Object... params){
        logger.info("exec sql :{}",sql);
        try {
            DataSourceByC3p0.getQueryRunner().update(sql,params);
        } catch (SQLException e) {
            logger.error(CONTENT,e);
        }
    }

    public void update(String env,String sql){
        logger.info("exec sql :{}",sql);
        try {
            DataSourceByC3p0.getQueryRunner(env).update(sql);
        } catch (SQLException e) {
            logger.error(CONTENT,e);
        }
    }


    public void exec(){
        DataSourceByC3p0.getQueryRunner();
    }


}
